var SAPP = function () {
  this._preate = null
  this._back_first = null

  this._init()
}

SAPP.prototype = {
  _init: function () {
    this.sappConfig = JSON.parse(plus.storage.getItem("sapp_config"))
    // 拦截Taro.navigateTo
    if (typeof Taro != "undefined") {
      // 多webview模式
      if (!this.sappConfig.singleWebview) {
        Taro.navigateTo = this.navigateTo.bind(this)
        Taro.redirectTo = this.navigateTo.bind(this)
        Taro.navigateBack = this.navigateBack.bind(this)
      }
      // debugger
      Taro.getEnv = this.getEnv.bind( this )
      // this.log_info("Taro method register done")
    } else {
      this.log_error("Taro is undefined, load fail")
    }
    // plus.navigator.setStatusBarStyle("light")
    if (window.sapp) {
      this.log_info("sapp plugin alreday load")
      return
    }

    this.sappConfig.singleWebview
      ? this.log_info("sapp webview is single modes")
      : this.log_info("sapp webview is multiple modes")
    // plus.navigator.setStatusBarBackground("#FFFFFF")
    // 按键返回监听
    plus.key.addEventListener("backbutton", this.navigateBack.bind(this), false)
    this.log_info("sapp plugin load success")
    // // 注册分享服务
    this._getShareService()
  },

  /*
   * @name: 获取应用首页BaseURL
   * @params: null
   * @return: string
   * @desc: 开发环境 http://www.xxxx.com/index.html; 生产环境 dist/index.html
   */
  _getBaseURL: function () {
    var launch_path = this.sappConfig.launch_path
    return launch_path
  },

  /*
   * @name: 预加载tabbar view
   * @params:
   * @return: boolen
   */
  _preateCreateTabView: function () {},

  // taro的首页路由，需要和app的首页路由转换
  _taroHomepageRouterChange: function () {},

  /*
   * @name: 检查url是否为tabbar
   * @params:
   * *    @url: 页面url
   * @return: boolen
   */
  _pathIsTabbar: function (url) {
    var tabBar = Store.getState().tabBar
    var tabList = tabBar.current.data
    var result = []
    if (tabList) {
      result = tabList.filter(function (item) {
        return item.pagePath == url.split("?")[0]
      })
      // if(url == this.sappConfig.launch_path)
    }
    return result.length > 0
  },

  /*
   * @name: 查找webview是否已经存在
   * @params:
   * *    @id: webview的id
   * @return: boolen
   */
  findWebViewById: function (id) {
    var all = plus.webview.all()
    var result = all.filter(function (item) {
      return item.id == id
    })
    return result
  },

  /*
   * @name: 导航
   * @params:
   *    @url: 页面url
   *    @params: 扩展参数
   *    @animate: 动画
   * @return: null
   */
  navigateTo: function (data) {
    var url = data.url
    var params = {} || data.params
    var animate = "slide-in-right" || params.animate
    var baseUrl = this._getBaseURL()
    if (this._pathIsTabbar(url)) {
      animate = "none"
    }
    if (!/^http|https/.test(baseUrl)) {
      baseUrl = "_www/dist/index.html"
    }

    var view = baseUrl + "#" + url
    this.log_info("view: " + view)
    // debugger

    var findResult = this.findWebViewById(url.split("?")[0])


    if (findResult.length > 0) {
      this.log_info("navigateTo: " + findResult[0].id)
      if (findResult[0].id == this.sappConfig.homePage) {
        plus.webview.getLaunchWebview().show()
      } else {
        findResult[0].show( animate )
        findResult[0].reload()
      }
    } else {
      var _openw = plus.webview.create(
        view,
        // 页面id不带参数
        url.split("?")[0],
        {
          scrollIndicator: "none",
          scalable: false,
          popGesture: "none",
        },
        params
      )
      // _openw.setJsFile("_www/js/shopex-app.js")
      _openw.show(animate)
    }
    setTimeout(
      function () {
        // webview 垃圾回收
        this._webViewGarbage(url)
      }.bind(this),
      200
    )

    // this._openw.addEventListener( 'loaded', this._handleWebviewOnload(animate), false)
  },

  /*
   * @name: 回退页面
   * @return: null
   */
  navigateBack: function () {
    var self = this
    var wobj = plus.webview.currentWebview()
    wobj.canBack(function (e) {
      if (e.canBack) {
        //webview history back
        window.history.back()
      } else {
        self.log_info("wobj id: " + wobj.id)
        if (wobj.id === plus.runtime.appid) {
          // 首页
          // 首次按键，提示‘再按一次退出应用’
          if (!self._back_first) {
            self._back_first = new Date().getTime()
            self.toast("再按一次退出应用")
            setTimeout(function () {
              self._back_first = null
            }, 2000)
          } else {
            if (new Date().getTime() - self._back_first < 2000) {
              plus.runtime.quit()
            }
          }
        } else {
          //webview close or hide
          wobj.close()
        }
      }
    })
  },

  // 垃圾回收
  _webViewGarbage: function (url) {
    // 当前运行页面是底部tab关联页面，需要垃圾回收处理
    var isTabPage = this._pathIsTabbar(url)
    if (!isTabPage) {
      return
    }
    var allWebview = plus.webview.all()
    allWebview.forEach(
      function (webview) {
        if (!this._pathIsTabbar(webview.id) && webview.id != "HBuilder") {
          webview.close("none")
        }
      }.bind(this)
    )
  },

  // 原生toast
  toast: function (title) {
    plus.nativeUI.toast(title, {
      verticalAlign: "center",
    })
  },

  /*
   * @name: 获取支付方式
   * @return: array
   */
  getPayList: function () {
    var self = this
    // 获取支付通道
    this.pays = {}
    return new Promise(function (resolve, reject) {
      plus.payment.getChannels(
        function (channels) {
          var result = []
          self.log_info("getPayList: " + JSON.stringify(channels))
          for (var i in channels) {
            self.pays[channels[i].id] = channels[i]
            result.push({
              id: channels[i].id,
              name: channels[i].description,
            })
          }
          // console.log('getPayList: ', result)
          resolve(result)
        },
        function (e) {
          self.toast("获取支付通道失败：" + e.message)
          reject(e)
        }
      )
    })
  },

  /*
   * @name: 支付调用
   * @params:
   *    @id: 支付id, wxpay, alipay
   *    @order_params: 订单信息
   * @return: array
   */
  payment: function (params) {
    var self = this
    var payid = params.id || ""
    var order = params.order_params || {}

    if (!this.pays) {
      this.getPayList().then(function () {
        self.payment(params)
      })
      // self.toast("请获取支付通道")
    }

    var channel = this.pays[payid]
    this.log_info("payment: " + JSON.stringify(params))
    return new Promise(function (resolve, reject) {
      if (!channel.serviceReady) {
        var txt = null
        switch (payid) {
          case "alipay":
            txt =
              "检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？"
            break
          default:
            txt =
              "系统未安装“" +
              channel.description +
              "”服务，无法完成支付，是否立即安装？"
            break
        }
        plus.nativeUI.confirm(
          txt,
          function (e) {
            if (e.index == 0) {
              channel.installService()
              return
            }
          },
          channel.description
        )
        reject(txt)
      } else {
        plus.payment.request(
          channel,
          order,
          function (result) {
            resolve(result)
          },
          function (e) {
            self.toast("支付失败：" + e.message)
            reject(e)
          }
        )
      }
    })
  },

  // 获取分享服务
  _getShareService: function () {
    var self = this
    this.shareServices = {}
    plus.share.getServices(
      function (data) {
        self.log_info("shareServcies: " + JSON.stringify(data))
        for (var item in data) {
          self.shareServices[data[item].id] = data[item]
        }
      },
      function (err) {
        self.toast("获取分享服务列表失败：" + err.message)
      }
    )
  },

  share: function (options) {
    var default_options = {
      url: "", // 分享url
      title: "", // 分享标题
      content: "", // 分享内容
      img: "", // 分享图片
      shareContent: "link", // link: 链接 img: 海报 wxmini: 小程序
      icons: {
        'wxfriend': 'bbc-icon-pengyouquan',
        'weixin': 'bbc-icon-weixin1',
        'sinawb': 'bbc-icon-weibofenxiangye',
        'link': 'bbc-icon-fuzhilianjie1',
        'download': 'bbc-icon-baocuntupian'
      },
      shareBtns: [
        {
          name: '分享链接',
        }
      ],
      btns: [
        {
          name: "朋友圈",
          icon: "bbc-icon-pengyouquan",
          key: "weixin",
          disabled: false,
        },
        { name: "微信", icon: "bbc-icon-weixin1", key: "wx", disabled: false },
        {
          name: "新浪微博",
          icon: "bbc-icon-weibofenxiangye",
          key: "sina",
          disabled: false,
        },
        {
          name: "复制链接",
          icon: "bbc-icon-fuzhilianjie1",
          key: "link",
          disabled: false,
        },
        {
          name: "下载图片",
          icon: "bbc-icon-baocuntupian",
          key: "download",
          disabled: true,
        }
      ]
    }

    // this.options = $.extend({}, this.defaults, opt)
  },

  // 分享 (微信、微博、小程序...)
  // share: function ( parmas ) {
    
  // },

  // 复制到剪贴板
  copyToClip: function (content) {
    switch (plus.os.name) {
      case "iOS":
        var UIPasteboard = plus.ios.importClass("UIPasteboard")
        var generalPasteboard = UIPasteboard.generalPasteboard()
        // 设置文本内容
        generalPasteboard.setValueforPasteboardType(
          content,
          "public.utf8-plain-text"
        )
        break
      case "Android":
        var context = plus.android.importClass("android.content.Context")
        var main = plus.android.runtimeMainActivity()
        var clip = main.getSystemService(context.CLIPBOARD_SERVICE)
        plus.android.invoke(clip, "setText", content)
        break
    }
    this.toast("复制成功")
  },

  // 获取剪贴板
  getClip: function () {
    var content
    switch (plus.os.name) {
      case "iOS":
        var UIPasteboard = plus.ios.importClass("UIPasteboard")
        var generalPasteboard = UIPasteboard.generalPasteboard()
        content = generalPasteboard.valueForPasteboardType(
          "public.utf8-plain-text"
        )
        break
      case "Android":
        var context = plus.android.importClass("android.content.Context")
        var main = plus.android.runtimeMainActivity()
        var clip = main.getSystemService(context.CLIPBOARD_SERVICE)
        content = plus.android.invoke(clip, "getText")
        break
    }
    return content
  },

  // 下载图片, 网路图片、base64

  /*
   * @name: 获取环境
   * @params:
   * @return: string
   */
  getEnv: function () {
    return "SAPP"
  },

  log_info: function (msg) {
    console.log("%c [mui-taro] " + msg, "color:#00f;")
  },

  log_error: function (msg) {
    console.log("%c [mui-taro] " + msg, "color:#f00;")
  },

  /*
   * @name: 第三方登录
   * @params:
   *    @type: 登录方式 wx weibo qq
   * @return:
   */
  otherLogin: function (params) {},

  // 分享

  /*
   * 
   */
  setStorageSync: function (key, value) {
    debugger
		this.log_info("setItem: " + key)
    plus.storage.setItem(key, value)
  },

  getStorageSync: function ( key ) {
    this.log_info("getItem: " + key)
    plus.storage.getItem(key)
  },
	
	removeStorageSync: function(key) {
		this.log_info('removeitem: ' + key)
		plus.storage.removeItem(key)
	}
}

// SAPP.prototype._handleWebviewOnload = function (animate) {
//   setTimeout(
//     function () {
//       this._openw.showed = true
//       console.log("animate: ", animate)
//       this._openw.show()
//     }.bind(this),
//     10
//   )
// }
window.sapp = new SAPP()
